|
|
|
| |
|
|
|
|
The SQL statement on which you base the comparison statement must be a SELECT statement. This statement must also be enclosed in parentheses and is referred to as a subquery. |
|
|
|
|
|
|
|
|
|
|
In the exercise, the SELECT statement contained within the parentheses (the sqlstatement, or subquery) is executed first to determine which authors sold more than 500 books in the first quarter. The SELECT statement outside of the parentheses (the main query) is then executed upon the result set created by the subquery. The IN keyword instructs the SELECT FROM Authors statement to take only those records that were extracted by the subquery. |
|
|
|
|
|
|
|
|
Other keywords that can be used in the expression include ANY and ALL. Also, numeric expression such as > and < can be used in conjunction with the keyword to make comparisons. |
|
|
|
|
|
|
|
|
For example, if you use the syntax > ANY in comparing the main query with the subquery (WHERE AUID > ANY), your result set displays all records from the main query that have a value greater than any value extracted from the subquery. Using > ALL (WHERE AUID > All) extracts only those records that are greater in value than every record extracted by the subquery. |
|
|
|
|
|
|
|
|
Without the ability to use nested SQL statements, the preceding exercise would have required you to perform a JOIN on the two tables, or build a table to store the subqueries result set, and then execute the main query on the table. The use of nested SQL SELECT statements can be a great time saver. |
|
|
|
|
|
|
|
|
Today you learned how to create basic SQL statements that select data from existing tables. You learned that the most fundamental form of the SQL statement is the SELECT_FROM clause. This clause is used to select one or more columns from a table and display the results of that statement in a result set, or view. |
|
|
|
|
|
|
|
|
You also learned about the optional clauses that you can add to the SELECT_FROM clause: |
|
|
|
|
|
|
|
|
· The WHERE clause: Used to limit the rows in the result set using logical comparisons (for example, WHERE Table.Name = "SMITH") and to link two tables in a single, nonupdateable, view (for example, WHERE Table1.Name = Table2.Name). |
|
|
|
|
|
|
|
|
· The ORDER BY clause: Used to control the order in which the result set is displayed (for example, ORDER BY Name ASC). |
|
|
|
|
|
|
|
|
· The GROUP BY clause: Used to create a subtotal result set based on a break column (for example, GROUP BY Name). |
|
|
|
|
|